package com.admin.servlet;

import com.admin.bean.Advert;
import com.admin.dao.advertDao;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.io.*;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;


public class advertAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } // 解析request请求
        Iterator iter = items.iterator();// 遍历表单中提交过来的内容
        Advert advert = new Advert();
        boolean flag = true;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) { // 如果是表单域 ，就是非文件上传元素
                String value = item.getString("UTF-8"); // 获取value属性的值，这里需要指明UTF-8格式，否则出现中文乱码问题
                if (item.getFieldName().equals("advertId")) {// 对应form中属性的名字
                    advert.setAdvertId(value);
                } else if (item.getFieldName().equals("url")) {
                    advert.setUrl(value);
                } else if (item.getFieldName().equals("describe")) {
                    advert.setAdvertDescribe(value);
                }
            } else {
                String filename = item.getName(); // 文件的名字
                String imgname = filename.substring(0, filename.indexOf("."));
                String path = request.getServletContext().getRealPath("images/advert"); //target找到img位置
                Long time = Calendar.getInstance().getTimeInMillis();  //时间戳，保证文件命名不重复
                String imgurl = "img_" + time + ".jpg";//图片名称
                advert.setPicture("/images/advert/" + imgurl);

                System.out.println(request.getServletContext().getContextPath());
                File saveFile = new File(path + "/" + imgurl); // 定义一个file指向一个具体的文件
                try {
                    item.write(saveFile);// 把上传的内容写到一个文件中
                    System.out.println("上传到" + path + "成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("文件" + path + "为空");
                    flag = false;
                }
            }
        }
        PrintWriter out=response.getWriter();
        if (flag)
        {
            new advertDao().addAdvert(advert);
            out.println("<script language='javascript'>alert('添加成功')</script>");
        }
        else {
            //添加失败
            out.println("<script language='javascript'>alert('添加失败，请确认数据重新添加')</script>");
        }
        out.println("<script language='javascript'>window.location.href='add_Advert.jsp'</script>");
    }
}
